package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.mapper.AdminUserLoginMapper;
import com.zhentao.model.common.admin.dto.AdminLoginDto;
import com.zhentao.model.common.admin.pojo.AdminUser;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.AdminUserLoginService;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class AdminUserLoginServiceImpl implements AdminUserLoginService {
    @Resource
    private AdminUserLoginMapper adminUserLoginMapper;

    /**
     * 平台管理端登录
     * @param loginDto 登录所用到的参数
     * @return
     */
    @Override
    public ResponseResult addLogin(AdminLoginDto loginDto) {
        //校验是否为空
        if (StringUtils.isBlank(loginDto.getName()) || StringUtils.isBlank(loginDto.getPassword()) ){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //根据登录用户名进行查找是否存在
        AdminUser adminUser = adminUserLoginMapper.selectOne(Wrappers.<AdminUser>lambdaQuery().eq(AdminUser::getName, loginDto.getName()));
        if (adminUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取盐
        String salt = adminUser.getSalt();
        //获取正确密码
        String password = adminUser.getPassword();

        //将用户登录的密码进行使用MD5加密
        String md5Pass = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));

        //进行比对密码
        if (!password.equals(md5Pass)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //生成token
        String token = AppJwtUtil.getToken(Long.valueOf(adminUser.getId()));
        //创建map集合
        HashMap<String, Object> map = new HashMap<>();
        //将token放入集合当中
        map.put("token",token);

        //将用户信息放入map当中
        adminUser.setPassword(null);
        adminUser.setSalt(null);
        map.put("adminLoginUser",adminUser);

        return ResponseResult.okResult(map);
    }

}
